//
//  LXAcount.m
//  微了个小博
//
//  Created by imera on 15/9/22.
//  Copyright (c) 2015年 imera. All rights reserved.
//

#import "LXAcount.h"

#define AcountFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"acount.data"]

@implementation LXAcount

/**
 *  保存用户信息
 *
 */
+ (void)saveAcount:(LXAcount *)acount
{
    NSDate *date = [NSDate date];
    
    acount.expiresTime = [date dateByAddingTimeInterval:acount.expires_in];
    
   [NSKeyedArchiver archiveRootObject:acount toFile:AcountFilePath];
}
/**
 *  获取用户信息
 *
 */
+ (instancetype)Acount
{
    LXAcount *acount = [NSKeyedUnarchiver unarchiveObjectWithFile:AcountFilePath];

    NSDate *now = [NSDate date];
    
    if([now compare:acount.expiresTime] == NSOrderedAscending)//没有过期
    {
        return acount;
    }else{
        return nil;
    }
    
    return acount;
}

+ (instancetype)accountWithDict:(NSDictionary *)dict
{
     return [[self alloc]initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
    if(self = [super init]){
        //kvo模式
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

/**
 *  从文件中解析时候调用
 *
 */
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super init]){
        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.expires_in = [aDecoder decodeInt64ForKey:@"expires_in"];
        self.remind_in  = [aDecoder decodeInt64ForKey:@"remind_in"];
        self.uid = [aDecoder decodeInt64ForKey:@"uid"];
        self.expiresTime = [aDecoder decodeObjectForKey:@"expiresTime"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
    }
    return self;
}

/**
 *  将对象写入文件的时候调用
 *
 */
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeInt64:self.expires_in forKey:@"expires_in"];
    [aCoder encodeInt64:self.remind_in forKey:@"remind_in"];
    [aCoder encodeInt64:self.uid forKey:@"uid"];
    [aCoder encodeObject:self.expiresTime forKey:@"expiresTime"];
    [aCoder encodeObject:self.name forKey:@"name"];
}

@end
